#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
# =============================================================================
#      FileName: base_httpserver.py
#          Desc: 
#        Author: Xue Ning
#         Email: ning.xue@duomi.com
#       Version: 0.0.1
#    LastChange: 2015-03-18 20:25:28
#       History:
# =============================================================================
'''

from ConfigParser import ConfigParser
from tornado import gen
from tornado.web import RequestHandler
from engine import Daemon
from dm_py_util import DEBUG_LOG, ERROR_LOG, WARN_LOG, INFO_LOG, INIT_LOG, BUSINESS_LOG


class BaseHTTPServer(object):
    def __init__(self, *handler):
        self.http_application = None
        self.config = None
        self.handler = handler
        self.access_log_file = None
        self.app_log_file = None
        self.gen_log_file = None

    def init(self, config):
        if not config:
            raise
        self.config = config
        config_parser = ConfigParser()
        config_parser.read(config)
        log_config = config_parser.get('Log', 'log_config')
        INIT_LOG(log_config)

        server_port = eval(config_parser.get('HTTPServer', 'server_port'))
        server_location = eval(config_parser.get('HTTPServer', 'server_location'))
        server_num = eval(config_parser.get('HTTPServer', 'work_num'))
        self.stdout = config_parser.get('Daemon', 'stdout_file')
        self.stderr = config_parser.get('Daemon', 'stderr_file')
        self.pid_file = config_parser.get('Daemon', 'pid_file')

        try:
            self.access_log_file = config_parser.get('Tornado', 'access_log')
            self.app_log_file = config_parser.get('Tornado', 'app_log')
            self.gen_log_file = config_parser.get('Tornado', 'gen_log')
        except Exception as e:
            pass

        self.port = server_port or 16666
        self.work_num = server_num or 0
        self.locations = server_location or ['base']
        self.log_init()

    def log_init(self):
        import logging
        import tornado.log
        DATEFMT = '%Y/%m/%d %I:%M:%S'
        if self.app_log_file:
            app_log_handler = logging.FileHandler(self.app_log_file)
            app_log_handler.setFormatter(tornado.log.LogFormatter(datefmt=DATEFMT))
            tornado.log.app_log.addHandler(app_log_handler)
            tornado.log.enable_pretty_logging(logger=tornado.log.app_log)

        if self.gen_log_file:
            gen_log_handler = logging.FileHandler(self.gen_log_file)
            gen_log_handler.setFormatter(tornado.log.LogFormatter(datefmt=DATEFMT))
            tornado.log.gen_log.addHandler(gen_log_handler)
            tornado.log.enable_pretty_logging(logger=tornado.log.gen_log)

        if self.access_log_file:
            access_log_handler = logging.FileHandler(self.access_log_file)
            access_log_handler.setFormatter(tornado.log.LogFormatter(datefmt=DATEFMT))
            tornado.log.access_log.addHandler(access_log_handler)
            tornado.log.enable_pretty_logging(logger=tornado.log.access_log)

    def init_master(self, config):
        DEBUG_LOG('init master...')

    def init_worker(self, config):
        DEBUG_LOG('init worker...')

    def serve_forever(self, debug=True):
        import tornado.httpserver
        import tornado.ioloop
        import tornado.netutil
        import tornado.web
        import os
        self.pid = os.getpid()
        if not debug:
            self.daemon = Daemon(stdout=self.stdout, stderr=self.stderr,
                                 pidfile=self.pid_file)
            self.daemon.run()
        self.init_master(self.config)
        app = tornado.web.Application(list(zip(self.locations, self.handler)))
        http_server = tornado.httpserver.HTTPServer(app, xheaders=True)
        sockets = tornado.netutil.bind_sockets(self.port)
        tornado.process.fork_processes(self.work_num)
        self.init_worker(self.config)
        http_server.add_sockets(sockets)
        tornado.ioloop.IOLoop.instance().start()



if __name__ == '__main__':
    class Test(RequestHandler):
        def get(self):
            self.finish('successs!!!')
    class Test2(RequestHandler):
        def get(self):
            self.finish('successs2!!!')

    s = BaseHTTPServer(Test, Test2)
    s.init('./conf/server.ini')
    s.serve_forever(True)
